<template>
  <div class="exam-list-container">
    <div class="header-section">
      <div class="header-content">
        <div class="title-area">
          <div class="icon-wrapper">
            <el-icon class="header-icon"><Files /></el-icon>
          </div>
          <div class="title-text">
            <h1>试题试卷管理</h1>
            <p>管理您的所有试卷，支持在线预览和导出功能</p>
          </div>
        </div>
        <div class="stats-area">
          <div class="stat-item">
            <div class="stat-number">{{ exams.length }}</div>
            <div class="stat-label">总试卷数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ publishedCount }}</div>
            <div class="stat-label">已发布</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ draftCount }}</div>
            <div class="stat-label">草稿</div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-content">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner">
          <el-icon class="rotating"><Loading /></el-icon>
        </div>
        <p>正在加载试卷数据...</p>
      </div>

      <div v-else-if="exams.length === 0" class="empty-container">
        <div class="empty-illustration">
          <el-icon><DocumentAdd /></el-icon>
        </div>
        <h3>暂无试卷</h3>
        <p>您还没有创建任何试卷，开始创建您的第一份试卷吧！</p>
      </div>

      <div v-else class="exam-grid">
        <div 
          v-for="(exam, index) in exams" 
          :key="exam.id" 
          class="exam-card"
          :style="{ animationDelay: (index * 0.07) + 's' }"
          @click="previewExam(exam.id)"
        >
          <div class="card-header">
            <div class="exam-id">#{{ exam.id }}</div>
            <div class="exam-status">
              <span :class="`status-badge status-${exam.status.toLowerCase()}`">
                {{ getStatusText(exam.status) }}
              </span>
            </div>
          </div>
          
          <div class="card-body">
            <h3 class="exam-title">{{ exam.title }}</h3>
            <div class="exam-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(exam.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="card-footer">
            <div class="action-buttons">
              <el-button 
                class="action-btn preview-btn" 
                @click.stop="previewExam(exam.id)"
              >
                <el-icon><View /></el-icon>
                <span>预览</span>
              </el-button>
              <el-button 
                class="action-btn export-btn" 
                @click.stop="exportExam(exam.id)"
              >
                <el-icon><Download /></el-icon>
                <span>导出</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import examService from '../../services/examService';
import api from '../../services/api';
import { 
  View, 
  Download, 
  Files, 
  Calendar, 
  Loading, 
  DocumentAdd 
} from '@element-plus/icons-vue';

const loading = ref(true);
const exams = ref([]);
const router = useRouter();

// 计算统计数据
const publishedCount = computed(() => 
  exams.value.filter(exam => exam.status === 'PUBLISHED').length
);
const draftCount = computed(() => 
  exams.value.filter(exam => exam.status === 'DRAFT').length
);

const fetchExams = async () => {
  try {
    loading.value = true;
    exams.value = await examService.getAllExams();
  } catch (error) {
    ElMessage.error(error.message || '获取试卷列表失败');
  } finally {
    loading.value = false;
  }
};

const previewExam = (id) => {
  router.push({ name: 'TeacherExamPreview', params: { id } });
};

const exportExam = async (id) => {
  ElMessage.info('正在准备导出文件，请稍候...');
  try {
    const response = await api.get(`/api/exams/${id}/export`, {
      responseType: 'blob',
    });

    const contentDisposition = response.headers['content-disposition'];
    let fileName = `exam_${id}.docx`;
    if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename\*?=(UTF-8'')?(.+)/);
        if (fileNameMatch && fileNameMatch.length > 2) {
            fileName = decodeURIComponent(fileNameMatch[2]);
        }
    }

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();

    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('文件已开始下载！');

  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出文件失败，请联系管理员。');
  }
};

const getStatusText = (status) => {
  if (status === 'PUBLISHED') return '已发布';
  if (status === 'FINISHED') return '已结束';
  return '草稿';
};

const formatDate = (dateArray) => {
  // 1. 首先检查输入是否是一个有效的数组
  if (!Array.isArray(dateArray) || dateArray.length < 3) {
    // 如果数据格式不正确，返回一个提示信息
    return '日期格式错误';
  }

  // 2. 从数组中提取年月日等信息
  //    关键：将数组中的月份（dateArray[1]）减 1，以匹配 JavaScript 的 0-indexed 月份
  const year = dateArray[0];
  const month = dateArray[1] - 1; // 月份从 0 开始，所以需要减 1
  const day = dateArray[2];
  const hours = dateArray[3] || 0;
  const minutes = dateArray[4] || 0;
  const seconds = dateArray[5] || 0;

  // 3. 使用这些数字参数创建 Date 对象
  const date = new Date(year, month, day, hours, minutes, seconds);

  // 4. 检查日期是否有效，防止出现类似 [2025, 13, 1] 这样的错误数据
  if (isNaN(date.getTime())) {
    return '无效日期';
  }

  // 5. 进行格式化并返回
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

onMounted(fetchExams);
</script>

<style scoped>
/* General Style */
.exam-list-container {
  min-height: 100vh;
  background-color: #f4f7fa; /* 原始背景色 */
  font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

/* Header Section */
.header-section {
  background: #ffffff; /* 原始背景色 */
  border-bottom: 1px solid #e0e6ed; /* 原始边框色 */
  padding: 2rem 0; /* 增加垂直内边距，更大气 */
}

.header-content {
  max-width: 1280px; /* 稍微加宽以适应现代屏幕 */
  margin: 0 auto;
  padding: 0 2.5rem; /* 增加水平内边距 */
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-area {
  display: flex;
  align-items: center;
  gap: 1.5rem; /* 增加图标与文字的间距 */
}

.icon-wrapper {
  width: 52px; /* 稍微增大 */
  height: 52px;
  background-color: #e8f0fe; /* 原始背景色 */
  border-radius: 14px; /* 更柔和的圆角 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-icon {
  font-size: 26px; /* 稍微增大 */
  color: #409EFF; /* 原始图标色 */
}

.title-text h1 {
  margin: 0;
  color: #303133; /* 原始文字色 */
  font-size: 26px; /* 增加字号 */
  font-weight: 700; /* 加粗 */
}

.title-text p {
  margin: 6px 0 0 0; /* 增加与标题的间距 */
  color: #909399; /* 原始文字色 */
  font-size: 15px; /* 增加字号 */
}

/* Stats Area */
.stats-area {
  display: flex;
  gap: 3rem; /* 增加统计项间距 */
}

.stat-item {
  text-align: center;
  color: #606266; /* 原始文字色 */
}

.stat-number {
  font-size: 24px; /* 增加字号 */
  font-weight: 700; /* 加粗 */
  color: #303133; /* 原始文字色 */
}

.stat-label {
  font-size: 13px; /* 增加字号 */
  margin-top: 6px;
  text-transform: uppercase;
  letter-spacing: 0.5px; /* 增加字母间距 */
}

/* Main Content */
.main-content {
  max-width: 1280px;
  margin: 0 auto;
  padding: 3rem 2.5rem; /* 增加内边距 */
}

/* Loading & Empty States (保持原始颜色) */
.loading-container, .empty-container { text-align: center; padding: 5rem 0; color: #909399;}
.loading-spinner { font-size: 48px; margin-bottom: 1rem; color: #409EFF; }
.rotating { animation: rotate 1.5s linear infinite; }
@keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.empty-illustration { font-size: 64px; margin-bottom: 1.5rem; color: #c0c4cc; }
.empty-container h3 { margin: 0 0 1rem 0; font-size: 22px; color: #303133; }
.empty-container p { color: #909399; font-size: 16px; }

/* Exam Grid */
.exam-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(330px, 1fr)); /* 微调最小宽度 */
  gap: 2.5rem; /* 增大卡片间距 */
}

/* --- 卡片美化核心 --- */
.exam-card {
  background: #ffffff;
  border-radius: 18px; /* 更柔和的圆角 */
  overflow: hidden;
  cursor: pointer;
  /* 核心：更柔和、更有层次感的阴影 */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03), 
              0 4px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e0e6ed;
  display: flex;
  flex-direction: column;
  /* 核心：更平滑、优雅的过渡动画曲线 */
  transition: transform 0.35s cubic-bezier(0.25, 0.8, 0.25, 1),
              box-shadow 0.35s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.exam-card:hover {
  /* 核心：更明显的悬浮效果 */
  transform: translateY(-8px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.04), 
              0 12px 24px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 1.75rem 0.5rem; /* 增加内边距 */
}

.exam-id {
  font-size: 14px; /* 增大字号 */
  color: #909399; /* 原始颜色 */
  font-weight: 500;
}

/* Status Badges (保持原始颜色) */
.status-badge { padding: 5px 12px; border-radius: 99px; font-size: 13px; font-weight: 600; } /* 增大字号 */
.status-published { background-color: #e6f7f2; color: #00875a; }
.status-finished { background-color: #f0f2f5; color: #606266; }
.status-draft { background-color: #fffbe6; color: #d48806; }

/* Card Body & Footer */
.card-body {
  padding: 1rem 1.75rem;
  flex-grow: 1;
}

.exam-title {
  margin: 0 0 1rem 0;
  font-size: 19px; /* 增大字号 */
  font-weight: 600;
  color: #303133; /* 原始颜色 */
  line-height: 1.5; /* 增加行高 */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.75rem; /* 增加图标与文字间距 */
  color: #909399; /* 原始颜色 */
  font-size: 14px;
}
.meta-item .el-icon { font-size: 16px; }

.card-footer {
  padding: 0.5rem 1.75rem 1.5rem; /* 调整内边距 */
  margin-top: auto; /* 让页脚在卡片内容不足时也能置底 */
}

.action-buttons {
  display: flex;
  gap: 1rem; /* 增加按钮间距 */
  margin-top: 1rem;
}

/* --- 按钮美化核心 --- */
.action-btn {
  flex: 1;
  height: 42px; /* 增加高度 */
  border-radius: 12px; /* 更柔和的圆角 */
  font-weight: 600; /* 加粗 */
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  border: none;
  /* 核心：更平滑的过渡动画 */
  transition: all 0.25s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.action-btn:hover {
  /* 核心：增加悬浮时的轻微上移效果 */
  transform: translateY(-2px);
}

.preview-btn {
  background: #409EFF; /* 原始颜色 */
  color: white;
}
.preview-btn:hover {
  background: #337ecc; /* 原始颜色 */
}

.export-btn {
  background: #f0f2f5; /* 原始颜色 */
  color: #606266; /* 原始颜色 */
}
.export-btn:hover {
  background: #e4e7ed; /* 原始颜色 */
}

/* Responsive Design */
@media (max-width: 768px) {
  .header-content { flex-direction: column; gap: 2rem; text-align: center; }
  .stats-area { justify-content: center; }
  .exam-grid { grid-template-columns: 1fr; }
  .main-content { padding: 2rem 1.5rem; }
}

/* Card Animation */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(25px); /* 增加初始位移 */
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.exam-card {
  /* 核心：更平滑、优雅的入场动画 */
  animation: fadeInUp 0.6s cubic-bezier(0.25, 0.8, 0.25, 1) forwards;
  opacity: 0;
}
</style>